<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0;">
      <el-form :inline="true" :model="query">
        <el-form-item>
          <el-input v-model="query.keyword" placeholder="请输入关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="departmentList.rows"
              highlight-current-row v-loading="listLoading"
              @selection-change="selectedChange"
              style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="sn" label="部门编号" width="150">
      </el-table-column>
      <el-table-column prop="name" label="部门名" width="150">
      </el-table-column>
      <el-table-column prop="manager.username" label="经理" width="150">
      </el-table-column>
      <el-table-column prop="parent.name" label="父部门" width="150">
      </el-table-column>
      <el-table-column prop="dirPath" label="路径" width="150">
      </el-table-column>
      <el-table-column prop="state" label="状态" width="120" >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.state === 1" type="success">启用</el-tag>
          <el-tag v-else type="error">停用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

<!--    工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.selected.length===0">批量删除</el-button>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="query.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="query.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="departmentList.total"
          style="float:right;">
      </el-pagination>
    </el-col>

<!--    编辑界面-->
    <el-dialog title="新增/保存"
               :visible.sync="formVisible"
               :close-on-click-modal="false">
      <el-form :model="departmentForm" label-width="80px" :rules="formRules" ref="editForm">
        <el-form-item label="部门名" prop="name">
          <el-input v-model="departmentForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="简介" prop="intro">
          <el-input v-model="departmentForm.intro" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="经理" prop="manager">
          <template>
            <el-select v-model="departmentForm.manager.id" placeholder="请选择">
              <el-option
                  v-for="item in managers"
                  :key="item.id"
                  :label="item.username"
                  :value="item.id">
              </el-option>
            </el-select>
          </template>
        </el-form-item>
        <el-form-item label="父部门" prop="parent">
          <el-cascader v-model="departmentForm.parent"
                       :options="parentDepartment"
                       :props="{
							            checkStrictly: true,
							            label:'name',
							            value:'id'
							         }"
                       clearable>
          </el-cascader>
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-radio-group v-model="departmentForm.state">
            <el-radio class="radio" :label="1">启用</el-radio>
            <el-radio class="radio" :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="formVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
export default {
  mounted() {
    this.getDepartment()
  },
  data(){
    return{
      formRules:{
        name: [
          {required: true, message: '请输入活动名称', trigger: 'blur'},
          {min: 3, max: 7, message: '长度在 3 到 5 个字符', trigger: 'blur'}
        ]
      },
      selected:[],
      listLoading: false,
      query:{
        keyword:"",
        currentPage:1,
        pageSize:10
      },
      departmentList:{
        rows:[],
        total:0
      },
      formVisible: false,
      departmentForm:{
        id:null,
        name:"",
        intro:"",
        manager:{
          id:null,
          username:""
        },
        parent:{
          id:null,
          name:""
        },
        path:"",
        state: 0
      },
      parentDepartment:[],
      managers:[]
    }
  },
  methods:{
    search(){
      this.query.currentPage=1
      this.getDepartment()
    },
    getParent(){
      this.$http.get("/department/tree")
          .then(result => {
            result = result.data
            this.parentDepartment = result.data
          })
          .catch(result => {
            this.$message({message: result.message, type: 'error'});
          });
    },
    getManager(){
      this.$http.get("/employee")
          .then(result => {
            result = result.data
            this.managers = result.data
          })
          .catch(result => {
            this.$message({message: result.message, type: 'error'});
          });
    },
    saveSubmit(){
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          let param = this.departmentForm
          let temp = param.parent
          param.parent = {id:temp[temp.length - 1]}
          console.log(param)
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            // 调用后端接口-axios
            this.$http.put("/department", param)
                .then(result => {
                  // 获取后端返回的结果
                  result = result.data; // {success:true,message:""}
                  if (result.success) {
                    this.$message({ message: "保存成功!", type: 'success' });
                    // 关闭弹框
                    this.formVisible = false;
                    this.departmentForm = {
                      id:null,
                      name:"",
                      intro:"",
                      manager:{
                        id:null,
                        username:""
                      },
                      parent:{
                        id:null,
                        name:""
                      },
                      path:"",
                      state: 0
                    }
                    this.query.currentPage = 1;
                    this.getDepartment();
                  } else {
                    this.$message({ message: result.message, type: 'error' });
                  }
                })
                .catch(() => {
                  this.departmentForm = {
                    id:null,
                    name:"",
                    intro:"",
                    manager:{
                      id:null,
                      username:""
                    },
                    parent:{
                      id:null,
                      name:""
                    },
                    path:"",
                    state: 0
                  }
                  this.$message({ message: "网络异常,请检查网络!", type: 'error' });
                })
          });
        }
      })
    },
    handleAdd(){
      this.getParent()
      this.getManager()
      this.departmentForm = {
        id:null,
        name:"",
        intro:"",
        manager:{
          id:null,
          username:""
        },
        parent:{
          id:null,
          name:""
        },
        path:"",
        state: 0
      }
      this.formVisible = true
    },
    handleSizeChange(val){
      this.query.pageSize = val;
      this.query.currentPage = 1;
      this.getDepartment()
    },
    handleCurrentChange(val){
      this.query.currentPage = val
      this.getDepartment()
    },
    handleDel(index,row){
      this.$confirm('确认删除吗？', '提示', {type: 'warning'})
          .then(() => {
            let id = row.id
            this.$http.delete("/department/" + id)
            .then(result =>{
              result = result.data
              if (result.success){
                this.$message({ message: "删除成功!", type: 'success' });
                this.query.currentPage = 1
                this.getDepartment()
              } else {
                this.$message({ message: result.message, type: 'error' });
              }
            })
            .catch(() => {
              this.$message({message: '删除失败!', type: 'error'});
            })
          }).catch(() => {
        this.$message({message: '已取消删除!', type: 'info'});
      });
    },
    handleEdit(index,row){
      this.getParent()
      this.getManager()
      let temp = [];
      if (row.path) {
        let array = row.path.split("/")
        for (let i = 1; i < array.length - 1; i++) {
          temp.push(parseInt(array[i]))
        }
      }
      this.departmentForm = row
      this.departmentForm.parent = temp;
      this.formVisible = true
      if (!this.departmentForm.manager) {
        this.departmentForm.manager = {
          id: null,
          username: ""
        }
      }
      if (!this.departmentForm.parent) {
        this.departmentForm.parent = {
          id: null,
          name: ""
        }
      }
    },
    batchRemove(){
      let ids = this.selected.map(item =>item.id)
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        // 2 调后端的删除接口
        this.$http.patch("/department", ids)
            .then(result => {
              result = result.data; // {success:true,message:""}
              if (result.success) {
                // 提示"删除成功"
                this.$message({ message: "删除成功!", type: 'success' });
                // 删除成功以后,要重新查询数据,并且要从第一页开始进行查询
                this.query.currentPage = 1;
                // 调用查询方法
                this.getDepartment();
                // this.search();
              } else {
                this.$message({ message: result.message, type: 'error' });
              }
            })
            .catch(result => {
              this.$message({ message: "网络异常,请检查网络!", type: 'error' });
            })
      }).catch(() => {
        this.$message({ message: '已取消删除!', type: 'info' });
      });
    },
    selectedChange: function (selected) {
      this.selected = selected;
    },
    getDepartment(){
      this.$http.post("/department",this.query)
      .then(result =>{
        result = result.data
        if (result.success){
          this.departmentList = result.dataObj
        } else{
          this.$message({
            message: result.data.message,
            type: 'error'
          });
        }

      })
      .catch(result =>{
        this.$message({
          message: '网络异常',
          type: 'error'
        });
      })
    }
  }
}
</script>

<style scoped>

</style>